//
//  MainScene.cpp
//  PlantNanny
//
//  Created by Joueu on 14-12-18.
//
//

#include "MainScene.h"
#include "DictionaryKeyNames.h"
#include "ShareToWeiXinLayer.h"
#include "ShowCup.h"
#include "BottomTableViewCell.h"
#include "AddCupLayer.h" 
#include "ElementLayer.h"
#include "AnimationUtil.h"
#include "Resource.h"
#include "StatusScene.h"
#include "DataCenter.h"

#define POPUP_LAYER_ZORDER         200
float ITEM_GAP = 100;

MainScene *MainScene::createScene()
{
    MainScene *main = new MainScene();
    if (main && main -> init()) {
        main -> autorelease();
    }
    else {
        CC_SAFE_RELEASE(main);
    }
    return main;
}

bool MainScene::init()
{
    if (!Scene::init()) {
        return false;
    }
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    this -> preLoadResource();
#endif
    
    m_layer = Layer::create();
    this -> addChild(m_layer, 0);
    
    m_itemsLayer = Layer ::create();
    this -> addChild(m_itemsLayer, 10);
    
    m_popUpLayer = Layer::create();
    this -> addChild(m_popUpLayer, POPUP_LAYER_ZORDER);

    this -> createBackground();
    this -> createMenu();
    this -> createDrinkBtn();
    
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    this -> createPlantAndPot();
#endif

    this -> createTouchListener();
    this -> createBottomLayer();
    
    return true;
}

void MainScene::createBackground()
{
    windows = Sprite::create("background_d-568h@2x.png");
    windows -> setAnchorPoint(Point(0, 0));
    windows -> setPosition(Point(0, 0));
    m_layer -> addChild(windows, 0);
    
    background = Sprite::create(DataCenter::getInstance() -> getUsingBackgroundSceneName());
    background -> setAnchorPoint(Point(0,1));
    background -> setPosition(Point(0, VISIBLESIZE.height));
    m_layer -> addChild(background, -1);
    
    auto backWhite = LayerColor::create(Color4B(255,255,255,255), VISIBLESIZE.width, VISIBLESIZE.height);
    m_layer -> addChild(backWhite, -10);
}

void MainScene::createMenu()
{
    m_element = Element::createWithItemNameAndNum(10);
    m_element -> setPosition(Point(0.15 *VISIBLESIZE.width, 0.9 * VISIBLESIZE.height));
    m_element -> addTouchEventListener(CC_CALLBACK_2(MainScene::elementPressed, this));
    m_itemsLayer -> addChild(m_element);
    
    m_btnPer = BtnPer::create();
    m_btnPer -> setPosition(Point(0.75 *VISIBLESIZE.width, 0.9 *VISIBLESIZE.height));
    m_btnPer -> addTouchEventListener(CC_CALLBACK_2(MainScene::btnPerPressed, this));
    m_itemsLayer -> addChild(m_btnPer);
    
    m_showSubMenuBtn = MenuItemImage::create(
                                             "btn_menu@2x.png",
                                             "btn_menu_p@2x.png",
                                             CC_CALLBACK_1(MainScene::showSubMenuBtnPressed, this)
                                             );
    m_showSubMenuBtn -> setPosition(Point(0.89 * VISIBLESIZE.width, MENU_HEIGHT));
    
    auto shareBtn = MenuItemImage::create(
                                        "btn_share@2x.png",
                                        "btn_share_p@2x.png",
                                        CC_CALLBACK_1(MainScene::shareBtnPressed, this)
                                        );
    shareBtn -> setPosition(Point(0.32 * VISIBLESIZE.width, MENU_HEIGHT));
    
    Menu *menu = Menu::create(m_showSubMenuBtn,shareBtn, NULL);
    menu -> setPosition(Point(0, 0));
    m_itemsLayer -> addChild(menu , 100);
    
    this -> createSubMenu();
}

void MainScene::createSubMenu()
{
    auto m_gradenBtn = MenuItemImage::create(
                                             "btn_garden@2x.png",
                                             "btn_garden_p@2x.png",
                                             CC_CALLBACK_1(MainScene::btnPressed, this));
    m_gradenBtn -> setPosition(Point(m_showSubMenuBtn -> getPosition()));
    auto m_shopBtn = MenuItemImage::create(
                                           "btn_shop@2x.png",
                                           "btn_shop_p@2x.png",
                                           CC_CALLBACK_1(MainScene::shopBtnPressed, this));
    m_shopBtn -> setPosition(Point(m_showSubMenuBtn -> getPosition()));
    auto m_sceneBtn = MenuItemImage::create(
                                            "btn_scene@2x.png",
                                            "btn_scene_p@2x.png",
                                            CC_CALLBACK_1(MainScene::sceneBtnPressed, this));
    m_sceneBtn -> setPosition(Point(m_showSubMenuBtn -> getPosition()));
    auto m_configBtn = MenuItemImage::create(
                                             "btn_config@2x.png",
                                             "btn_config_p@2x.png",
                                             CC_CALLBACK_1(MainScene::btnPressed, this));
    m_configBtn -> setPosition(Point (m_showSubMenuBtn -> getPosition()));
    m_subMenu = Menu::create(m_gradenBtn, m_shopBtn, m_sceneBtn, m_configBtn,NULL);
    //    m_subMenu = Menu::create(m_gradenBtn, m_shopBtn, NULL);
    m_subMenu -> setPosition(Point(0, 0));
    
    long childrenCount = m_subMenu -> getChildren().size();
    for (int i = 0; i < childrenCount; i++) {
        MenuItemSprite *sprite =(MenuItemSprite *) m_subMenu ->getChildren().at(i);
        sprite -> setRotation(180);
    }
    m_itemsLayer -> addChild(m_subMenu, 10);
    m_subMenu -> setVisible(false);
}

void MainScene::createDrinkBtn()
{
    Size size = Director::getInstance() -> getVisibleSize();
    m_progress = XKProgressTimer::createWithBG("ring_progress.png", "ring_bg.png");
    
    m_progress -> setPosition(Point(0.85 *size.width, 182));
    //0.16 * size.height
    m_progress -> setPercentage(0);
    m_progress -> setType(ProgressTimer::Type::RADIAL);
    m_layer -> addChild(m_progress, 10);
    
    m_bottleBtn = Sprite::create(DataCenter::getInstance() -> getUsingCupName());
    m_bottleBtn -> setPosition(m_progress -> getPosition());
    m_layer -> addChild(m_bottleBtn, 11);
    auto listener = EventListenerTouchOneByOne::create();
    listener -> setSwallowTouches(true);
    
    listener -> onTouchBegan = [&](Touch *touch, Event *event){
        auto progressTo = ProgressTo::create(1.8, 100);
        auto target = static_cast<Sprite *>(event -> getCurrentTarget());
        Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);
        if(rect.containsPoint(locationInNode)){
            CallFunc *callfunc = CallFunc::create([&](){
                // to do list
            });
            auto delay = DelayTime::create(0.5);
            CallFunc *callfunc2 = CallFunc::create([&](){
                auto layer = ElementLayer::createWith("注意","劲酒虽好，可不要贪杯哦~","plant_type_1@2x.png");
                m_popUpLayer -> addChild(layer);
            });
            PlayDrinkSound
            Action *sequence = Sequence::create(progressTo, callfunc,delay, callfunc2,NULL);
            
            sequence -> setTag(10086);
            m_progress -> runAction(sequence);

            return true;
        }
        return false;
    };
    
    listener -> onTouchMoved = [&](Touch *touch, Event *event){
        auto target = static_cast<Sprite *>(event -> getCurrentTarget());
        Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(-s.width * 0.2, -s.height * 0.2, s.width * 1.2, s.height * 1.2);
        if(!rect.containsPoint(locationInNode)){
            m_progress -> stopActionByTag(10086);
            m_progress -> setPercentage(0);
            CocosDenshion::SimpleAudioEngine::getInstance() -> stopAllEffects();
        }
    };
    
    listener -> onTouchEnded = [&](Touch *touch, Event *event){
        if (m_progress -> getPercentage() != 100) {
            m_progress -> stopActionByTag(10086);
            CocosDenshion::SimpleAudioEngine::getInstance() -> stopAllEffects();
        }else {
            DataCenter::getInstance() -> drink();
            m_btnPer -> updatePer(15);
        }
        m_progress -> setPercentage(0);
    };
    
    Director::getInstance() -> getEventDispatcher() -> addEventListenerWithSceneGraphPriority(listener, m_bottleBtn);
}


void MainScene::createPlantAndPot()
{
    Point originPoint = Director::getInstance() -> getVisibleOrigin();
    Size visibleSize = Director::getInstance() -> getVisibleSize();
    
    m_pot = Sprite::create("pot.png");
    Size potSize = m_pot -> getContentSize();
    m_pot -> setPosition(Point(visibleSize.width * 0.52f, visibleSize.height *0.22f));
    
//    m_plant = Sprite::create("plant1.png");
    m_plant = Sprite::createWithSpriteFrameName("plant_1_1_n_2_a0.png");
    Size plantSize = m_plant -> getContentSize();
    log("%f, %f", plantSize.width, plantSize.height);
    m_plant -> setPosition(Vec2(visibleSize.width * 0.52f, m_pot -> getPositionY() + potSize.height * 0.5f + plantSize.height * 0.5f - 6) );
    auto listener = EventListenerTouchOneByOne::create();
    listener -> setSwallowTouches(true);
    listener -> onTouchBegan = [](Touch *touch, Event *event){
        auto target = static_cast<Sprite *>(event -> getCurrentTarget());
        Vec2 locationInNode = target->convertToNodeSpace(touch->getLocation());
        Size s = target->getContentSize();
        Rect rect = Rect(0, 0, s.width, s.height);
        if(rect.containsPoint(locationInNode)){
            return true;
        }
        return false;
    };
    listener -> onTouchEnded = [&](Touch *touch, Event *event){
        auto animation = AnimationUtil::getInstance() -> createAnimationWithFirstName("plant_1_1_n_2_a");
        if (animation != NULL) {
            animation -> setLoops(1);
            animation -> setDelayPerUnit(0.08f);
            auto target = static_cast<Sprite *>(event -> getCurrentTarget());
            long number = target -> getNumberOfRunningActions();
            if  (number == 0){
                Point position = target -> getPosition();
                target -> runAction(Animate::create(animation));
                PlayTouchSound
            }
        }
    };
    ///222 156
    Director::getInstance() -> getEventDispatcher() -> addEventListenerWithSceneGraphPriority(listener, m_plant);
    m_layer -> addChild(m_pot,10);
    m_layer -> addChild(m_plant,25);
}

void MainScene::createTouchListener()
{
    auto listener = EventListenerTouchOneByOne::create();
    listener -> setSwallowTouches(true);
    listener -> onTouchBegan = [&](Touch *touch, Event *event){
        float height = Director::getInstance() -> getVisibleSize().height;
        float locationY = touch -> getLocation().y;
        
        
        if (m_subMenu -> isVisible() && !m_changScene) {
            this -> setSubMenuVisible(false);
        }
        
        if (m_moveUp || m_changScene) {
            return locationY > 0.25 *height ? true : false;
        }else {
            return locationY < 0.07*height ? true :false;
        }
    };
    
    listener -> onTouchEnded = [&](Touch *touch, Event *event){
        if (m_changScene && m_sceneLayer != NULL) {
            auto moveAction = MoveTo::create(0.3, Point(0, -200));
            auto callFunc = CallFunc::create([&](){
                m_sceneLayer -> removeFromParentAndCleanup(true);
                m_sceneLayer = NULL;
            });
            m_sceneLayer -> runAction(Sequence::create(moveAction, callFunc, NULL));
            m_changScene = !m_changScene;
            this -> setMenuAndDrinkBtnVisible(true);
            return ;
        }
        if (m_moveUp) {
            //            m_visibleLayer -> beforeMoveDown();
            this -> moveUpOrDown(m_moveUp);
            
//            m_itemsLayer -> setVisible(true);
        }else{
//            m_visibleLayer -> beforeMoveUp();
            this -> moveUpOrDown(m_moveUp);
//            m_itemsLayer -> setVisible(false);
        }
//        m_moveUp = !m_moveUp;
    };
    Director::getInstance() -> getEventDispatcher() -> addEventListenerWithSceneGraphPriority(listener, windows);
}

void MainScene::createBottomLayer()
{
    m_bottoLayer = Layer::create();
    m_layer -> addChild(m_bottoLayer, 0);
    
    Sprite *background = Sprite::create("background_bottom_d@2x.png");
    Size bgSize = background -> getContentSize();
    Sprite *dock = Sprite::create("wooden-dock_d@2x.png");
    dock -> setPosition(Point(0.5 *bgSize.width, 0.5 * bgSize.height));
    background -> addChild(dock, 1);
    background -> setAnchorPoint(Point(0, 1));
    m_bottoLayer -> addChild(background, 0, 0);
    
//    cupsPageView = XKPageView::create(BOTTOMCELL_SIZE, this);
//    cupsPageView -> setDirection(ScrollView::Direction::HORIZONTAL);
//    cupsPageView -> setPosition(Point(-VISIBLESIZE.width, -180));
//    m_bottoLayer -> addChild(cupsPageView);
    
    m_tableView = TableView::create(this, Size(VISIBLESIZE.width,320));
    m_tableView -> setDelegate(this);
    m_tableView -> setDirection(extension::ScrollView::Direction::HORIZONTAL);
    m_tableView -> setPosition(Point(- VISIBLESIZE.width,-180));
    m_bottoLayer -> addChild(m_tableView);
    
//    _cupNameVector.push_back(Value("btn_addcup@2x.png"));
    
}

void MainScene::addCup(Ref *pSender)
{
    __Dictionary *dict = dynamic_cast<__Dictionary *>(pSender);
    int opa = ((__Integer *)(dict -> objectForKey("opacity"))) -> getValue();
//    const char *fileName = ((__String *)(dict -> objectForKey("fileName"))) -> getCString();
    int type = ((__Integer *)(dict -> objectForKey("Type"))) -> getValue();
    
    _cupCapVector.insert(_cupCapVector.begin(), Value(opa));
    _cupTypeVector.insert(_cupTypeVector.begin(), Value(type));
//    _cupNameVector.insert(_cupNameVector.begin(), Value(fileName));
    
    DataCenter::getInstance() -> setValueVectorForKey(_cupCapVector, kCupCapVector);
    DataCenter::getInstance() -> setValueVectorForKey(_cupTypeVector, kCupTypeVector);
    m_tableView -> reloadData();
}

void MainScene::deleteCup(cocos2d::Ref *pSender)
{
    __Dictionary *dict = dynamic_cast<__Dictionary *>(pSender);
    int index = ((__Integer *)(dict -> objectForKey("CellIndex"))) -> getValue();
    if (_cupTypeVector.size() > 2) {
        int delType = _cupTypeVector.at(index).asInt();
        int delCap = _cupCapVector.at(index).asInt();
        _cupTypeVector.erase(_cupTypeVector.begin() + index);
        _cupCapVector.erase(_cupCapVector.begin() + index);
        
        if (delType == DataCenter::getInstance() -> getUsingCupType() &&
            delCap == DataCenter::getInstance() -> getUsingCupCapacity()) {
            DataCenter::getInstance() -> setUsingCupCapacity(_cupCapVector.at(0).asInt());
            DataCenter::getInstance() -> setUsingCupType(_cupTypeVector.at(0).asInt());
            m_bottleBtn -> setTexture(DataCenter::getInstance() -> getUsingCupName());
        }
    }
    DataCenter::getInstance() -> setValueVectorForKey(_cupCapVector, kCupCapVector);
    DataCenter::getInstance() -> setValueVectorForKey(_cupTypeVector, kCupTypeVector);
    m_tableView -> reloadData();
}

void MainScene::changeTheDCup(cocos2d::Ref *pSender)
{
    __Dictionary *dict = dynamic_cast<__Dictionary *>(pSender);
    int type = ((__Integer *)(dict -> objectForKey("Type"))) -> getValue();
    int cap = ((__Integer *)(dict -> objectForKey("Capacity"))) -> getValue();
    DataCenter::getInstance() -> setUsingCupType(type);
    DataCenter::getInstance() -> setUsingCupCapacity(cap);
    m_bottleBtn -> setTexture(DataCenter::getInstance() -> getDCupNameByType(type));
    this -> moveUpOrDown(true);
}


void MainScene::changeTheTheme(Ref *pSender)
{
    background -> stopAllActions();
    __Dictionary *dict = dynamic_cast<__Dictionary *>(pSender);
    int type = ((__Integer *)(dict -> objectForKey("Type"))) -> getValue();
    auto actionOut = FadeTo::create(0.15f, 200);
    auto callFunc = CallFunc::create([&](){
        background -> setTexture(DataCenter::getInstance() -> getBackgroundSceneByType(type));
    });
    auto actionIn = FadeTo::create(0.45f, 255);
    background -> runAction(Sequence::create(actionOut, callFunc, actionIn, NULL)  );
    UserDefault::getInstance() -> setIntegerForKey(kBackgroundScene, type);
}

#pragma mark - tableViewDelegate

ssize_t MainScene::numberOfCellsInTableView(TableView *table)
{
    return _cupCapVector. size();
}

TableViewCell *MainScene::tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx)
{
    auto cell = table -> dequeueCell();
    
    if (!cell) {
//        auto cup = ShowCup::createWithNameAndCap(_cupNameVector.at(idx).asString(), _cupCapVector.at(idx).asInt());
        
        auto cup = ShowCup::createWithTypeAndCap((int)_cupTypeVector.at(idx).asInt(), _cupCapVector.at(idx).asInt());
        cup -> setPosition(Vec2(80,180));
        cup -> setTag(10086);
        cup -> setCellIndex(idx);
        cell = TableViewCell::create();
        cell -> addChild(cup);
    }else{
        auto cup = dynamic_cast<ShowCup *>(cell -> getChildByTag(10086));
        cup -> changeWithTypeAndCap((int)_cupTypeVector.at(idx).asInt(), _cupCapVector.at(idx).asInt());
        cup -> setCellIndex(idx);
    }
    return cell;
}

Size MainScene::cellSizeForTable(cocos2d::extension::TableView *table)
{
    Size visibleSize = Director::getInstance() -> getVisibleSize();
    return Size(visibleSize.width / 4, BOTTOMCELL_SIZE.height);
}

void MainScene::setSubMenuVisible(bool flag)
{
    if  (m_subMenu -> isVisible() == flag)
        return;
    
    float delayTime = 0.1f;
    if  (flag){
        PlayPositiveSound
        m_subMenu -> setVisible(true);
        long childrenCount = m_subMenu -> getChildren().size();
        for (int i = 0; i < childrenCount; i++) {
            MenuItemSprite *sprite =(MenuItemSprite *) m_subMenu ->getChildren().at(i);
            RotateBy *rotate = RotateBy::create(delayTime,-180);
            MoveTo *moveTo = MoveTo::create(delayTime, Point(m_showSubMenuBtn -> getPositionX(),m_showSubMenuBtn -> getPositionY() - (i + 1) * ITEM_GAP));
            Spawn *spawn = Spawn::create(rotate, moveTo, NULL);
            CallFunc *func = CallFunc::create([&](){
                m_showSubMenuBtn -> setEnabled(true);
            });
            Sequence *seque = Sequence::createWithTwoActions(EaseBackIn::create(spawn), func);
            sprite -> runAction(seque);
        }
    }else {
        PlayNegativeSound
        long childrenCount = m_subMenu -> getChildren().size();
        for (int i = 0; i < childrenCount; i++) {
            MenuItemSprite *sprite =(MenuItemSprite *) m_subMenu ->getChildren().at(i);
            RotateBy *rotate = RotateBy::create(delayTime,180);
            MoveTo *moveTo = MoveTo::create(delayTime, m_showSubMenuBtn -> getPosition());
            Spawn *spawn = Spawn::create(rotate, moveTo, NULL);
            CallFunc *func = CallFunc::create([&](){
                m_subMenu -> setVisible(false);
                m_showSubMenuBtn -> setEnabled(true);
            });
            Sequence *seque = Sequence::createWithTwoActions(spawn, func);
            sprite -> runAction(seque);
        }
    }
}


void MainScene::setMenuAndDrinkBtnVisible(bool flag)
{
    m_bottleBtn -> stopAllActions();
    if (flag == true) {
//        auto action2 = MoveTo::create(MOVEUP_TIME,Point(0, 0));
//        m_layer -> runAction(EaseBackOut::create(action2));
        m_itemsLayer -> setCascadeOpacityEnabled(true);
        auto action = FadeIn::create(FADE_TIME);
        auto callFunc = CallFunc::create([&](){
            m_itemsLayer -> setVisible(true);
        });
        m_itemsLayer -> runAction(Sequence::create(action, callFunc, NULL));
        
        m_progress -> setVisible(true);
        auto callFunc2 = CallFunc::create([&](){
            m_bottleBtn -> setPosition(m_progress -> getPosition());
        });
        m_bottleBtn -> runAction(Sequence::create( callFunc2,action -> clone(), NULL));
    }else {
//        auto action2 = MoveTo::create(MOVEUP_TIME,Point(0, 180));
//        m_layer -> runAction(EaseBackOut::create(action2));
        m_itemsLayer -> setCascadeOpacityEnabled(true);
        auto action = FadeOut::create(FADE_TIME);
        auto callFunc = CallFunc::create([&](){
            m_itemsLayer -> setVisible(false);
        });
        m_itemsLayer -> runAction(Sequence::create(action, callFunc, NULL));
        m_itemsLayer -> runAction(action);
        
        m_progress -> setVisible(false);
        auto callFunc2 = CallFunc::create([&](){
            m_bottleBtn -> setPosition(-500, 0);
        });
        m_bottleBtn -> runAction(Sequence::create(action -> clone(), callFunc2, NULL));
    }
}

void MainScene::moveUpOrDown(bool flag)
{
    setMenuAndDrinkBtnVisible(flag);
    if (flag) {
        auto action2 = MoveTo::create(MOVEUP_TIME,Point(0, 0));
        m_layer -> runAction(EaseBackOut::create(action2));
        auto cupsAction = MoveTo::create(FADE_TIME - 0.2f, Point(-VISIBLESIZE.width , -180));
        //        cupsPageView -> runAction(cupsAction);
        NotificationCenter::getInstance() -> postNotification("hideTheOpr", this);
        m_tableView -> runAction(cupsAction);
    }else{
        auto action2 = MoveTo::create(MOVEUP_TIME,Point(0, 180));
        m_layer -> runAction(EaseBackOut::create(action2));

        auto cupsAction = MoveTo::create(MOVEUP_TIME - 0.2f, Point(0 , -180));
//        cupsPageView -> runAction(cupsAction);
        m_tableView -> reloadData();
        m_tableView -> runAction(cupsAction);
    }
    m_moveUp = !m_moveUp;
}

#pragma mark - BtnPressed

void MainScene::elementPressed(Ref *pSender, ui::Button::TouchEventType type)
{
    if (type == ui::Button::TouchEventType::ENDED) {
        PlayPositiveSound
        auto elayer = ElementLayer::createWith();
        m_popUpLayer -> addChild(elayer);
    }
}


void MainScene::btnPerPressed(Ref *pSender, ui::Button::TouchEventType type)
{
    if (type == ui::Button::TouchEventType::ENDED) {
        PlayPositiveSound
        Director::getInstance() -> pushScene(TransitionMoveInL::create(0.3f, StatusScene::createScene()));
    }
}

void MainScene::shareBtnPressed(cocos2d::Ref *pSender)
{
//    CocosDenshion::SimpleAudioEngine::getInstance() -> playEffect("positive.mp3");
    PlayPositiveSound
    auto layer = ShareToWeiXinLayer::create();
    m_popUpLayer -> addChild(layer, 500);
}

void MainScene::showSubMenuBtnPressed(Ref *pSender)
{
    m_showSubMenuBtn -> setEnabled(false);
    if (m_subMenu -> isVisible()) {
        setSubMenuVisible(false);
    }
    else {
        setSubMenuVisible(true);
    }
}

void MainScene::btnPressed(Ref *pSender)
{
    
//    CocosDenshion::SimpleAudioEngine::getInstance() -> playEffect("positive.mp3");
        PlayPositiveSound
}

void MainScene::shopBtnPressed(Ref *pSender)
{
    
    //    CocosDenshion::SimpleAudioEngine::getInstance() -> playEffect("positive.mp3");
    PlayPositiveSound
}

void MainScene::sceneBtnPressed(Ref *pSender)
{
    //    CocosDenshion::SimpleAudioEngine::getInstance() -> playEffect("positive.mp3");
    PlayPositiveSound
    m_sceneLayer = ChangeSceneLayer::create();
    m_sceneLayer -> setPosition(Point(0, -200));
    m_popUpLayer -> addChild(m_sceneLayer, POPUP_LAYER_ZORDER);
    auto moveAction = MoveTo::create(0.3f, Point(0, 0));
    auto callFunc = CallFunc::create([&](){
        setMenuAndDrinkBtnVisible(false);
        m_changScene = true;
    });
    m_sceneLayer -> runAction(Sequence::create(moveAction, callFunc, NULL));
}

#pragma mark - delegate

Size MainScene::sizeForPerPage(XKPageView *pageView)
{
    return BOTTOMCELL_SIZE;
}

#pragma mark - Notification

void MainScene::addCupLayerPopUp(Ref *pSender)
{
//    if (cupsPageView -> getPositionX() != 0) {
//        return;
//    }
    if (m_tableView -> getPositionX() != 0) {
        return;
    }
    auto layer = AddCupLayer::create();
    this -> addChild(layer, 5000);
}

#pragma mark - preLoadResource
void MainScene::preLoadResource()
{
//    ValueVector vect;
//    vect.insert(vect.begin(), Value(0));
//    _cupCapVector = DataCenter::getInstance() -> getValueVectorByKey(kCupCapVector, vect);
//    _cupTypeVector = DataCenter::getInstance() -> getValueVectorByKey(kCupTypeVector, vect);
    
//    if (_cupCapVector.size() == 0 || _cupTypeVector.size() == 0) {
//        _cupCapVector.clear();
//        _cupTypeVector.clear();
//        _cupCapVector.insert(_cupCapVector.begin(), Value(0));
//        _cupTypeVector.insert(_cupTypeVector.begin(), Value(0));
//    }
    
    SpriteFrameCache::getInstance() -> addSpriteFramesWithFile("plant_1_1_n_2_anim.plist", "plant_1_1_n_2_anim-hd.png");
    SpriteFrameCache::getInstance() -> addSpriteFramesWithFile("plant_1_1_n_1_anim.plist", "plant_1_1_n_1_anim-hd.png");
}

void MainScene::initData()
{
    ValueVector vect;
    vect.insert(vect.begin(), Value(0));
    _cupCapVector = DataCenter::getInstance() -> getValueVectorByKey(kCupCapVector, vect);
    _cupTypeVector = DataCenter::getInstance() -> getValueVectorByKey(kCupTypeVector, vect);
    
    background -> setTexture(DataCenter::getInstance() -> getUsingBackgroundSceneName());
    m_bottleBtn -> setTexture(DataCenter::getInstance() -> getUsingCupName());
    
    m_tableView -> reloadData();
    m_btnPer -> updatePer(0);
}

void MainScene::onEnter()
{
    Scene::onEnter();
    this -> initData();
    NotificationCenter::getInstance() -> addObserver(this, callfuncO_selector(MainScene::addCupLayerPopUp), "PopUpAddCupLayer", NULL);
    NotificationCenter::getInstance() -> addObserver(this, callfuncO_selector(MainScene::addCup), "AddCup", NULL);
    NotificationCenter::getInstance() -> addObserver(this, callfuncO_selector(MainScene::deleteCup), "DeleteCup", NULL);
    NotificationCenter::getInstance() -> addObserver(this, callfuncO_selector(MainScene::changeTheDCup), "ChangeTheDCup", NULL);
    NotificationCenter::getInstance() -> addObserver(this, callfuncO_selector(MainScene::changeTheTheme), "ChangeTheTheme", NULL);
}

void MainScene::onExit()
{
    log("exit");
    Scene::onExit();
    NotificationCenter::getInstance() -> removeAllObservers(this);
    DataCenter::getInstance() -> setValueVectorForKey(_cupCapVector, kCupCapVector);
    DataCenter::getInstance() -> setValueVectorForKey(_cupTypeVector, kCupTypeVector);
}
